package com.tanhua.server.interceptor;

import com.tanhua.model.domain.User;
import com.tanhua.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/29 20:57
 *
 *  拦截器，处理token，并且将数据存放在ThreadLocal中
 *              如果校验Token失败就返回401
 */


public class TokenInterceptor extends HandlerInterceptorAdapter {

    // 拦截前执行。
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1. 获取请求头,获取token
        String token = request.getHeader("Authorization");
        // 2. 校验token
        boolean verifyToken = JwtUtils.verifyToken(token);
        if(!verifyToken){
            // 返回为登录状态码
            response.setStatus(401);
            return false;
        }

        // 获取手机号，id
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String phone = (String) claims.get("phone");

        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(phone);

        // 将用户信息存到ThreadLocal中
        UserHolderThreadLocal.set(user);

        return true;
    }

    // 在过滤之后清空ThreadLocal中的数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolderThreadLocal.delete();
    }
}
